import hashlib
from Crypto.Cipher import AES
import base64


# PKCS7补位函数
def pad(text):
    padding_size = AES.block_size - len(text) % AES.block_size
    padding = chr(padding_size) * padding_size
    return text + padding


# PKCS7去除补位函数
def unpad(text):
    padding_size = ord(text[-1])
    if padding_size < 1 or padding_size > AES.block_size:
        return text
    padding = text[-padding_size:]
    if not all(padding[i] == chr(padding_size) for i in range(padding_size)):
        return text
    return text[:-padding_size]


# 将公钥和私钥直接写如入方法，减少重复定义
# 如下
def aes_encrypt2(text):
    """AES加密"""
    key = '1234567890123456'
    iv = '1234567890123456'
    # 将明文进行PKCS7补位
    text = pad(text)
    # 创建AES对象
    aes = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))
    # 加密明文
    encrypted_text = aes.encrypt(text.encode('utf-8'))
    # 对加密结果进行Base64编码
    encrypted_text = base64.b64encode(encrypted_text).decode('utf-8')
    return encrypted_text


def aes_decrypt2(encrypted_text):
    """AES解密"""
    key = '1234567890123456'
    iv = '1234567890123456'
    # 对加密结果进行Base64解码
    encrypted_text = base64.b64decode(encrypted_text.encode('utf-8'))
    # 创建AES对象
    aes = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))
    # 解密密文
    decrypted_text = aes.decrypt(encrypted_text).decode('utf-8')
    # 去除PKCS7补位
    decrypted_text = unpad(decrypted_text)
    return decrypted_text


def check_password_strength(password):
    # 检查密码长度
    if len(password) < 8:
        return 0

    # 检查密码是否包含数字、字母和特殊字符
    has_digit = any(char.isdigit() for char in password)
    has_letter = any(char.isalpha() for char in password)
    has_special = any(not char.isalnum() for char in password)

    # 综合评估密码强度
    if has_digit and has_letter and has_special:
        return 2
    elif (has_digit and has_letter) or (has_digit and has_special) or (has_letter and has_special):
        return 1
    else:
        return 0


def md5_encrypt(input_string):
    """md5加密功能"""
    md5hash = hashlib.md5(input_string.encode())
    return md5hash.hexdigest()


def encrypt_vue(text):
    encrypted_text = ""
    for char in text:
        # 对每个字符进行简单的移位加密
        encrypted_text += chr((ord(char) + 10) % 256)
    return encrypted_text

